%% @author wenqi_zheng
%% @doc @todo Add description to examples1.


-module(examples1).

%% ====================================================================
%% API functions
%% ====================================================================
-export([start/2, server/1]).

start(Num, LPort)->		
	case gen_tcp:listen(LPort, [binary, {packet, 4}, {active, false}]) of
		{ok, Listen} ->
			start_servers(Num, Listen),
			{ok, Port} = inet:port(Listen),
			Port;
		{error, Reason} ->
			{error, Reason}
	end.


start_servers(0, _) ->
	ok;
start_servers(Num, Listen) ->
	spawn(?MODULE, server, [Listen]),
	start_servers(Num-1, Listen).


server(Listen) ->
	case gen_tcp:accept(Listen) of
		{ok, Socket}->
			loop(Socket),
			server(Listen);
		Other->
			io:format("acceptreturned ~w - goodbye!~n",[Other]),
			ok
	end.

loop(Socket) ->
	inet:setopts(Socket,[{active,once}]),
	receive
		{tcp, Socket, Data}->	
			Answer= process(Data), % Not implemented in this example
			gen_tcp:send(Socket, Answer),		
			loop(Socket);
		{tcp_closed, Socket}->
			io:format("Socket~w closed [~w]~n",[Socket, self()]),
			ok
	end.


process(Data)->
	io:format("~wServer received binary =~p~n",  [self(), Data]),
	Str = binary_to_term(Data),
	io:format("Server {unpacked} ~p~n", [Str]),
	Reply = lib_misc:string2value(Str),
	io:format("Server replying = ~p~n", [Reply]),
	term_to_binary(Reply).


%% ====================================================================
%% Internal functions
%% ====================================================================


